<?php

namespace Frieza\Modules\Diary\Controllers;

use Encore\Admin\Grid;
use Doraemon\model\Photos;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Layout\Row;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Hhz\AdministrativeRegion\Region;
use Doraemon\service\Videos\Videos as sVideos;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DecorationTask\UserDiaryBook;
use Doraemon\service\Diary\Manage as sDiaryManage;

class DiaryController extends Controller
{

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script(
            <<<EOF
$('input[type=radio][name=select_area]').on('ifChecked',function(){

    if(this.value == 1) {
        $("select.multiplearea").parent().parent().hide();
        $("select.province").parent().parent().show();
        $("select.city").parent().parent().show();
    }else {
        $("select.multiplearea").parent().parent().show();
        $("select.city").parent().parent().hide();
        $("select.province").parent().parent().hide();
    }
});
$('input[type=radio][name=select_area]:checked').trigger('ifChecked');
if($('input[type=radio][name=select_area]:checked').val() == null){
$('input[type=radio][name=select_area]:first').attr('checked', 'checked');
 $("select.multiplearea").parent().parent().show();
        $("select.city").parent().parent().hide();
        $("select.province").parent().parent().hide();
}

EOF
        );
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [$page, $pageSize];
        unset($params['page']);
        $where = [];

        unset($params['province']);
        if ($params['select_area'] == 1) {
            $params['multiplearea'] = [];
            $params['city'] = $params['city'];
        } elseif ($params['select_area'] == 0) {
            $params['city'] = '';
            $allCities = [];
            if (!empty($params['multiplearea'])) {
                foreach ($params['multiplearea'] as $provinceCode) {
                    $newCities = array_keys(Region::getCityListByProvinceCode((string)$provinceCode)) ?: [];
                    $allCities[] = $newCities;
                }
                $cities = [];
                array_map(function ($value) use (&$cities) {
                    $cities = array_merge($value, $cities);

                }, $allCities);
                $params['city'] = $cities;
            }

        }
        unset($params['multiplearea']);
        unset($params['select_area']);


        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }
        return $data;
    }

    public function index(Request $request, Content $content)
    {
        $request = $request->all();

        $currentFilterParam = [];
        if ($request['select_area'] == 1) {
            $currentFilterParam['province_id'] = $request['province'];
        }
        $request = self::_filterWhere($request);


        $this->_setScript();
        return $content
            ->header('日记管理')
            ->breadcrumb(
                ['text' => '日记列表', 'url' => '/diary/list']
            )
            ->body(self::_listAction($request, $currentFilterParam));

    }


    public function detail(Request $request, Content $content)
    {
        $request = $request->all();
        $request = self::_filterWhere($request);

        Admin::script($this->_imgScript());
        return $content
            ->header('日记管理')
            ->breadcrumb(
                ['text' => '查看日记', 'url' => '/diary/detail']
            )
            ->body($this->_detailAction($request))
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>");

    }


    public function setView(Request $request)
    {
        try {

            $result = sDiaryManage::setView($request->all());
            $json['result'] = $result;
            $json['request'] = $request->all();

            $status = true;
            $message = '操作成功';
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return response()->json(compact('status', 'message'));
    }

    /**
     * 废弃使用新的地址 ->'/admin/extend/area/get'
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @deprecated
     */
    public function area(Request $request)
    {
        $pid = $request->input('q', 0);
        $areas = \Doraemon\service\position\UserProfileModule\Area::getLocation($pid);
        $format = array_map(function ($k, $v) {
            return [
                'id' => $k,
                'text' => $v,
            ];
        }, array_keys($areas), $areas);
        return response()->json($format);
    }


    /**
     * @param array $request
     * @param array $currentFilterParam
     * @return string
     */
    private function _listAction(array $request, array $currentFilterParam)
    {

        $diaryBooks = sDiaryManage::getDiaryBookData($request);

        $gridModel = new pGridDataModel($diaryBooks['list'], $diaryBooks['total'], [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1],
        ]);

        return $this->_fillData2View($gridModel, $currentFilterParam);
        //
    }


    private function _detailAction(array $request)
    {


        $diaries = sDiaryManage::getDiaryByDiaryBookId($request);

        foreach ($diaries['list'] as &$diary) {
            if ($diary['show_type'] == Photos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($diary['video_id']);
                $diary['expand'] = $this->_getVideoExpand($videoInfo);
            } else {
                $picInfos = json_decode($diary['pic_list'], true) ?: [];
                $diary['expand'] = $this->_getPicExpand($picInfos);
            }
            $diary['expand'] .= $this->_getDivLine();
        }


        $gridModel = new pGridDataModel($diaries['list'], $diaries['total'], [
            'perPage' => $request['per_page'] ?: $request['LIMIT'][1],
        ]);


        return $this->_fillData2DetailView($gridModel);
    }


    /**
     * @param pGridDataModel $gridModel
     * @param array $currentFilterParam
     * @return string
     */
    private function _fillData2View(pGridDataModel &$gridModel, array $currentFilterParam)
    {

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($currentFilterParam) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            //过滤器
            $grid->filter(function (Grid\Filter $filter) use ($currentFilterParam) {
                $this->_gridFilter($filter, $currentFilterParam);
            });
            //列表内容
            $this->_gridForm($grid);

        });

        return $listGrid->render();
    }


    private function _gridFilter(Grid\Filter $filter, array $currentFilterParam)
    {

        $filter->disableIdFilter();
        $filter->column(6, function ($filter) {
            $filter->equal('diary_book_id', '日记本ID');
            $filter->equal('uid', '作者ID');

            $filter->in('last_stage_id', '最新阶段')->multipleSelect(function () {

                return sDiaryManage::getDecorationStage();
            });

            $filter->between('last_publish_time', '最新发布时间')->date();


        });


        $filter->column(6, function (Grid\Filter $filter) use ($currentFilterParam) {

            $filter->equal('is_designer', '是否关联设计师')
                ->radio(["否", "是"]);
            $filter->equal('is_decoration_company', '是否关联装企')
                ->radio(["否", "是"]);

            $filter->equal('show_status', '是否日记频道可见')
                ->radio(["否", "是"]);

            $top = Region::getProvincesList();

            $filter->equal('select_area', '地区')->radio([
                0 => '地区多选(支持到省和直辖市)',
                1 => '地区单查(支持到市、区)',
            ])->default(1);
            $filter->in('multiplearea', '地区(多选)')->multipleSelect($top);
            $filter->equal('province', '省')->select($top)->load('city',
                '/admin/extend/area/get');
            $all_city = Region::getCityListByProvinceCode((string)$currentFilterParam['province_id']);
            $filter->equal('city', '市/区')->select($all_city);
        });

        return $filter;

    }


    private function _gridForm(Grid &$grid)
    {

        $grid->column('日记本ID')->display(function () {
            return "<a href='/admin/diary/detail?diary_book_id={$this->id}' target='_blank' >$this->id</a>";
        });
        $grid->column('uid', '用户信息')->userBasicInfo()->width(150);

        $grid->column('admin_tag', '装修房屋信息')->display(function () {
            return "[居室]：" . $this->house_type . "<br>" .
                "[面积]：" . $this->house_area . "<br>" .
                "[所在地区]：" . $this->city . "<br>" .
                "[房屋类型]：" . $this->decoration_type . "<br>" .
                "[设计师]：" . $this->designer . "<br>" .
                "[装企]：" . $this->decoration_company . "<br>" .
                "[最新阶段]：" . $this->last_stage;

        })->width(200);

        $grid->column('wiki', '商品数')->width(150);
        $grid->column('last_publish_time', '最新日记发布时间')->width(200);
        $grid->column('diary_total', '累计日记数')->width(50);
        $grid->column('quality_diary_total', '精选及优质以上日记数')->width(150);

        $grid->column('interaction_total', '累计交互数')->width(100);
        $grid->column('user_follow_record_total', '累计被追更')->width(100);


        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableEdit();
            $actions->disableDelete();


            $actions->prepend("<a href='/admin/diary/detail?diary_book_id={$actions->row->id}' target='_blank' >查看</a>");

            $isViewText = $actions->row->show_status == UserDiaryBook::IS_VIEW_VISIBLE ? '设置为不可见' : '设置为可见';

            $actions->prepend('<p><a class="setView label  label-info" data-id="' . $actions->row->id . '" data-isView="' . $actions->row->show_status . '"  href="javascript:void(0);">' . $isViewText . '</a></p>');

        });

    }


    private function _setScript()
    {
        Admin::script(
            <<<EOF
              //日记频道是否可见
         $('.setView').unbind('click').click(function(){
            var id= $(this).data('id');
            var isView=$(this).data('isview');
            console.log(isView)
            var msg = '';
            if(isView == 1){
                msg = '确定要设置日记频道不可见么？'
            }else{
                msg = '确定要设置日记频道可见么？'
            }
            layer.confirm(msg, {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/diary/setView';
                let params = {diary_book_id:id,show_status:isView};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                      
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
EOF
        );
    }


    private function _fillData2DetailView(pGridDataModel &$gridModel)
    {
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            //过滤器
            $grid->filter(function (Grid\Filter $filter) {
                $this->_gridDetailFilter($filter);
            });

            $this->_gridDetailForm($grid);


        });

        return $listGrid->render();
    }


    private function _gridDetailFilter(Grid\Filter $filter)
    {

        $filter->disableIdFilter();

        $filter->column(6, function (Grid\Filter $filter) {

            $filter->equal('quality', '质量')->checkbox(Photos::QUALITY_DESC);
        });

        return $filter;

    }


    private function _gridDetailForm(Grid &$grid)
    {

        $grid->disableActions();

        $grid->column('note_id', 'ID')->expand(function () {
            return $this->expand;
        }, true)->width(150);

        $grid->column('sub_stage', '子阶段')->width(150);
        $grid->column('remark', '日记正文')->width(200);
        $grid->column('addtime', '发布时间')->width(200);
        $grid->column('quality', '日记质量分')->width(150);

        $grid->column('admin_tag', '交互情况')->display(function () {
            return "赞：" . $this->like . "<br>" .
                "评论：" . $this->comment . "<br>" .
                "收藏：" . $this->favorite . "<br>" .
                "分享：" . $this->share;

        })->width(200);


    }

    private function _imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });
SCRIPT;
    }

    private function _getVideoExpand($videoInfo)
    {
        $row = new Row();
        $row->column(4,
            "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));
        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function _getPicExpand($picInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }


}
